package com.veryUsedCar.config;

import com.veryUsedCar.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.spring.web.json.Json;
 
import java.util.*;
 
/**
 * 重新封装swagger返回信息（需要网关代理的项目都需要重新封装，对单机请求没有影响）
 */
@Slf4j
@ControllerAdvice(basePackages = "springfox.documentation.oas.web")
public class SwaggerHandle implements ResponseBodyAdvice<Object> {
 
    @Value("${spring.application.name}")
    private String applictionName;
 
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }
 
    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (object == null) {
            return null;
        }
        //获取请求头
        HttpHeaders headers = serverHttpRequest.getHeaders();
        Set<String> strings = headers.keySet();
        //判断请求是否经过网关转发
        boolean isForwarded = strings.contains("forwarded");
        if (isForwarded) {
            String x_forwarded_for = headers.get("x-forwarded-for").get(0);
            String x_forwarded_proto = headers.get("x-forwarded-proto").get(0);
            String x_forwarded_prefix = headers.get("x-forwarded-prefix").get(0);
            String x_forwarded_port = headers.get("x-forwarded-port").get(0);
            String x_forwarded_host = headers.get("x-forwarded-host").get(0);
            //重新组装servers(总感觉方法有点low。。。)
            Json jsons = (Json) object;
            String value = jsons.value();
            Map map = JsonUtil.toObject(value, Map.class);
            List<Map<String, String>> servers = new ArrayList<>();
            Map<String, String> server = new HashMap<>();
            server.put("url", x_forwarded_proto + "://" + x_forwarded_host + x_forwarded_prefix);
            server.put("description", applictionName);
            servers.add(server);
            map.put("servers", servers);
            return new Json(JsonUtil.toJson(map));
        } else {
            return object;
        }
    }
}